package com.ztc.util;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.MultiState;
import com.baidu.ueditor.define.State;

public class FileUtil {
	private String dir = null;//指定要列出文件的目录
	private String rootPath = null;//文件根目录
	private String[] allowFiles = null;//允许的文件类型
	private int count = 0;//每次列出文件数量
	
	public FileUtil ( Map<String, Object> conf ) {

		this.rootPath = (String)conf.get( "rootPath" );
		this.dir = (String)conf.get( "dir" );
		this.allowFiles = this.getAllowFiles( conf.get("allowFiles") );
		this.count = (Integer)conf.get( "count" );
		
	}
	
	public State listFile ( int index ) {
		State state = null;
		FtpUtil ftpUtil = new FtpUtil();
		try {
			List<String> list = ftpUtil.listFiles(this.dir, this.allowFiles);
			if ( index < 0 || index > list.size() ) {
				state = new MultiState( true );
			} else {
				Object[] fileList = Arrays.copyOfRange( list.toArray(), index, index + this.count );
				state = this.getState( fileList );
			}
			
			state.putInfo( "start", index );
			state.putInfo( "total", list.size() );
		} catch (Exception e) {
			return new BaseState( false, AppInfo.IO_ERROR );
		}
		
		return state;
		
	}
	
	private State getState ( Object[] files ) {
		
		MultiState state = new MultiState( true );
		BaseState fileState = null;
		
		String filePath = null;
		
		for ( Object obj : files ) {
			if ( obj == null ) {
				break;
			}
			filePath = (String)obj;
			fileState = new BaseState( true );
			fileState.putInfo( "url", PathFormat.format( this.getPath( filePath ) ) );
			state.addState( fileState );
		}
		
		return state;
		
	}
	
	private String getPath ( String path ) {
		
		path = path.replace( "\\", "/" );
		if(this.rootPath.endsWith("/")) {
			return path.replace( this.rootPath, "/" );
		}
		return path.replace(this.rootPath, "");
		
	}
	
	private String[] getAllowFiles ( Object fileExt ) {
		
		String[] exts = null;
		String ext = null;
		
		if ( fileExt == null ) {
			return new String[ 0 ];
		}
		
		exts = (String[])fileExt;
		
		for ( int i = 0, len = exts.length; i < len; i++ ) {
			
			ext = exts[ i ];
			exts[ i ] = ext.replace( ".", "" );
			
		}
		
		return exts;
		
	}
}
